#!/usr/bin/env python3
"""
Runtime mapping table extractor using memory dumps
Run this while Lingma is active
"""

import subprocess
import re
import struct

def find_lingma_process():
    """Find running Lingma process"""
    try:
        result = subprocess.run(['pgrep', '-f', 'Lingma'], 
                               capture_output=True, text=True)
        if result.returncode == 0:
            return result.stdout.strip().split()[0]
    except:
        pass
    return None

def dump_process_memory(pid):
    """Dump process memory using gcore"""
    try:
        subprocess.run(['sudo', 'gcore', pid], check=True)
        return f'core.{pid}'
    except subprocess.CalledProcessError:
        print(f"Failed to dump memory for PID {pid}")
        return None

def search_memory_dump(core_file):
    """Search memory dump for mapping table"""
    known_mappings = {
        0xa1: 0x6d,  # m
        0xf3: 0x6f,  # o  
        0x6b: 0x64,  # d
        0x31: 0x65,  # e
        0xb0: 0x6c,  # l
        0x69: 0x22,  # "
        0x01: 0x3a,  # :
        0x90: 0x20   # space
    }
    
    print(f"Searching memory dump {core_file}...")
    with open(core_file, 'rb') as f:
        data = f.read()
    
    candidates = []
    for offset in range(0, len(data) - 256, 8):
        segment = data[offset:offset + 256]
        
        matches = 0
        for src, dst in known_mappings.items():
            if segment[src] == dst:
                matches += 1
        
        if matches >= 6:
            print(f"Found mapping table at offset 0x{offset:x} ({matches}/8 matches)")
            with open(f'runtime_mapping_0x{offset:x}.bin', 'wb') as f:
                f.write(segment)
            candidates.append((offset, segment))
    
    return candidates

if __name__ == "__main__":
    print("Runtime Mapping Table Extractor")
    print("================================")
    
    pid = find_lingma_process()
    if not pid:
        print("❌ Lingma process not found")
        print("Please start Lingma and try again")
        exit(1)
    
    print(f"Found Lingma process: PID {pid}")
    
    core_file = dump_process_memory(pid)
    if not core_file:
        exit(1)
    
    candidates = search_memory_dump(core_file)
    if candidates:
        print(f"✅ Found {len(candidates)} mapping table candidates")
    else:
        print("❌ No mapping tables found in memory dump")
